Why Can I Change Struct's int[] Property from Method Without Specifying "ref"?

Posted by AMissico on Stack Overflow See other posts from Stack Overflow or by AMissico
Published on 2010-04-09T21:13:03Z Indexed on 2010/04/09 21:23 UTC
Read the original article Hit count: 277

Filed under:
|
|

From a method, I can pass a struct which contains an array of integers, and change the values in the array. I am not sure I understand fully why I can do this. Can someone please explain why I can change the values stored in the int[]?

    private void DoIt(){

        SearchInfo a = new SearchInfo();
        a.Index = 1;
        a.Map = new int[] { 1 };

        SearchInfo b = new SearchInfo();
        b.Index = 1;
        b.Map = new int[] { 1 };

        ModifyA(a);
        ModifyB(ref b);

        Debug.Assert(a.Index == 1);
        Debug.Assert(a.Map[0] == 1, "why did this change?");

        Debug.Assert(b.Index == 99);
        Debug.Assert(b.Map[0] == 99);

    }
    void ModifyA(SearchInfo a) {
        a.Index = 99;
        a.Map[0] = 99;
    }
    void ModifyB(ref SearchInfo b) {
        b.Index = 99;
        b.Map[0] = 99;
    }
    struct SearchInfo {
        public int[] Map;
        public int Index;
    }

© Stack Overflow or respective owner

Related posts about c#

Related posts about struct